import { Tooltip } from 'antd';
import { AnchorLinkItemProps } from 'antd/es/anchor/Anchor';
import React from 'react';

function getTextFromNode(children: any) {
    if (Array.isArray(children)) {
        return children.map(getTextFromNode).join("")
    } else if (typeof children === "string") {
        return children
    } else if (children && children.props && children.props.children) {
        return getTextFromNode(children.props.children)
    } else {
        return ""
    }
}
export const createCustomHeading = () => {
    let index = 0
    let items: AnchorLinkItemProps[] = []
    const CustomHeading = (props: any) => {
        const id = `heading-${index++}`
        const indent = parseInt(props.node.tagName.slice(1)) - 1
        const text = getTextFromNode(props.children)
        items.push({
            key: id,
            href: `#${id}`,
            title: <Tooltip title={text} placement="left">
                <span style={{
                    paddingLeft: indent + 'em',
                }}>
                    {text}
                </span>
            </Tooltip>,
        })
        return React.createElement(props.node.tagName, {
            id,
        }, props.children);
    }
    return [CustomHeading, items] as const
}
